package com.tms.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tms.permission.mapper.SystemPermissionMapper;
import com.tms.permission.mapper.SystemRoleMapper;
import com.tms.permission.mapper.SystemRolePermissionMapper;
import com.tms.permission.service.SystemPermissionService;
import com.tms.systemPermission.bean.SystemPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【system_permission(系统权限表)】的数据库操作Service实现
* @createDate 2025-03-24 23:13:54
*/
@Service
public class SystemPermissionServiceImpl extends ServiceImpl<SystemPermissionMapper, SystemPermission>
    implements SystemPermissionService {

    @Autowired
    private SystemPermissionMapper systemPermissionMapper;

    @Autowired
    private SystemRoleMapper systemRoleMapper;


    @Override
    public List<String> getPermissionCode(String userId) {
        //获取该用户权限码集合
       return systemPermissionMapper.getPermissionCodeByUserId(userId);
    }

    @Override
    public List<String> getRoleCode(String userId) {
        return systemRoleMapper.getSystemRoleMapper(userId);
    }

    @Override
    public List<SystemPermission> getMenuTree(String userId) {
        //获取用户拥有的所有权限
        List<SystemPermission> menuList = systemPermissionMapper.getPermissionByUserId(userId);

        //构建菜单树
        List<SystemPermission> systemPermissions = buildMenuTree(menuList);

        return systemPermissions;
    }

    // 构建菜单树
    private List<SystemPermission> buildMenuTree(List<SystemPermission> menuList) {
        // 创建一个Map以便快速查找
        Map<String, SystemPermission> permissionMap = menuList.stream()
                .collect(Collectors.toMap(SystemPermission::getId, Function.identity()));

        //TODO 排序

        // 创建一个列表用于存放根节点
        List<SystemPermission> menuTree = new ArrayList<>();

        for (SystemPermission permission : menuList) {
            // 如果是根节点（parentId为null或0），则添加到根节点列表
            if (permission.getParentId() == null || permission.getParentId().equals("0")) {
                menuTree.add(permission);
            } else {
                // 如果不是根节点，则找到其父节点并添加到父节点的children中
                SystemPermission parent = permissionMap.get(permission.getParentId());
                if (parent != null) {
                    parent.getChildren().add(permission);
                }
            }
        }
        return menuTree;
    }
}




